package com.xy.modulemain.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.xy.modulemain.bean.Item

/**
 * @ClassName BaseCustomView
 * @Author xy
 * @Date 2021/8/23 14:23
 * @Description 描述
 */
abstract class BaseCustomView<T : ViewDataBinding, S : Item> : LinearLayout, ICustomerView<S> {
    lateinit var dataBinding: T
    lateinit var viewModel: S  //这里的viewModel指的是 实体类 ， 暂时还没有用到

    constructor(context: Context?) : super(context) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init()
    }

    private fun init() {
        val inflater =
            this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        dataBinding = DataBindingUtil.inflate(
            inflater,
            getLayoutId(),
            this,
            false
        )

        dataBinding.root.setOnClickListener {
            onRootViewClick(it)
        }
        this.addView(dataBinding.root)
    }


    override fun setData(data: S) {
        viewModel = data
        setDataToView(data) //将数据与界面绑定
        if (dataBinding != null) {
            dataBinding.executePendingBindings()
        }
    }



    //设置布局
    abstract fun getLayoutId(): Int

    //将数据与界面绑定 （也可以在子类的方法里面使用点击方法）
    abstract fun setDataToView(data: S)

    //添加点击事件
    abstract fun onRootViewClick(view:View)
}